<template>
  <div ref="el" :class="className" :style="{ height, width }"></div>
</template>

<script setup lang="ts">
import { onMounted, onBeforeUnmount, ref, nextTick, watch, useTemplateRef } from 'vue'
import * as echarts from 'echarts'
import { debounce } from 'lodash-es'

// 引入 macarons 主题
import 'echarts/theme/macarons'

// 定义组件名称
defineOptions({
  name: 'LineChart',
})

// 定义图表数据接口
interface ChartData {
  xData?: string[]
  legendData?: string[]
  color?: string[]
  yData1?: number[]
  yData2?: number[]
}

// 定义组件属性
interface Props {
  className?: string
  width?: string
  height?: string
  autoResize?: boolean
  chartData?: ChartData
}

const props = withDefaults(defineProps<Props>(), {
  className: 'chart',
  width: '100%',
  height: '350px',
  autoResize: true,
  chartData: () => ({
    xData: [],
    legendData: [],
    color: [],
    yData1: [],
    yData2: [],
  }),
})

// 图表实例
const chart = ref<echarts.ECharts | null>(null)

// 获取 DOM 元素的引用
const elRef = useTemplateRef<HTMLDivElement | null>('el')

// Resize 相关逻辑
let sidebarElm: HTMLElement | null = null
let resizeHandler: (() => void) | null = null

const $_sidebarResizeHandler = (e: TransitionEvent) => {
  if (e.propertyName === 'width' && resizeHandler) {
    resizeHandler()
  }
}

const initListener = () => {
  resizeHandler = debounce(() => {
    resize()
  }, 100)
  window.addEventListener('resize', resizeHandler)

  sidebarElm = document.getElementsByClassName('sidebar-container')[0] as HTMLElement
  if (sidebarElm)
    sidebarElm.addEventListener('transitionend', $_sidebarResizeHandler as EventListener)
}

const destroyListener = () => {
  if (resizeHandler) {
    window.removeEventListener('resize', resizeHandler)
    resizeHandler = null
  }

  if (sidebarElm) {
    sidebarElm.removeEventListener('transitionend', $_sidebarResizeHandler as EventListener)
    sidebarElm = null
  }
}

const resize = () => {
  if (chart.value) {
    chart.value.resize()
  }
}

// 设置图表选项
const setOptions = (datas: ChartData) => {
  if (chart.value) {
    chart.value.setOption({
      xAxis: {
        data: datas.xData,
        boundaryGap: false,
        axisTick: {
          show: false,
        },
      },
      grid: {
        left: 10,
        right: 30,
        bottom: 20,
        top: 39,
        containLabel: true,
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
        },
        padding: [5, 10],
      },
      yAxis: {
        axisTick: {
          show: false,
        },
      },
      legend: {
        data: datas.legendData || [],
      },
      series: [
        {
          name: datas.legendData?.[0] || '',
          itemStyle: {
            normal: {
              color: datas.color?.[0] || '',
              lineStyle: {
                color: datas.color?.[0] || '',
                width: 2,
              },
            },
          },
          smooth: true,
          type: 'line',
          data: datas.yData1 || [],
          animationDuration: 2800,
          animationEasing: 'cubicInOut',
        },
        {
          name: datas.legendData?.[1] || '',
          smooth: true,
          type: 'line',
          itemStyle: {
            normal: {
              color: datas.color?.[1] || '',
              lineStyle: {
                color: datas.color?.[1] || '',
                width: 2,
              },
              areaStyle: {
                color: '#f3f8ff',
              },
            },
          },
          data: datas.yData2 || [],
          animationDuration: 2800,
          animationEasing: 'quadraticOut',
        },
      ],
    })
  }
}

// 初始化图表
const initChart = () => {
  if (elRef.value) {
    chart.value = echarts.init(elRef.value, 'macarons')
    setOptions(props.chartData)
  }
}

// 监听图表数据变化
watch(
  () => props.chartData,
  (newVal) => {
    setOptions(newVal)
  },
  { deep: true },
)

// 生命周期钩子
onMounted(() => {
  nextTick(() => {
    console.log('onMounted 111111111111111111')
    initChart()
    initListener()
  })
})

onBeforeUnmount(() => {
  if (!chart.value) {
    return
  }
  chart.value.dispose()
  chart.value = null
  destroyListener()
})
</script>
